<!-- views/sales/Commission.vue -->
<template>
  <div class="commission-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">销售提成管理</h1>
        <div class="status-badges">
          <el-tag type="success" class="total-badge">
            <el-icon><Money /></el-icon>
            提成总金额: ¥{{ stats.totalCommission }}
          </el-tag>
          <el-tag type="warning" class="pending-badge">
            <el-icon><Clock /></el-icon>
            待审核: ¥{{ stats.pendingCommission }}
          </el-tag>
          <el-tag type="primary" class="paid-badge">
            <el-icon><Check /></el-icon>
            已发放: ¥{{ stats.paidCommission }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-actions">
        <!-- 导出报表 -->
        <el-button 
          :icon="Download" 
          @click="exportCommissionReport"
        >
          导出报表
        </el-button>
        
        <!-- 批量操作 -->
        <el-button 
          :icon="Operation" 
          @click="showBatchOperations"
          :disabled="selectedItems.length === 0"
        >
          批量操作 ({{ selectedItems.length }})
        </el-button>
        
        <!-- 生成报表 -->
        <el-button 
          type="success" 
          :icon="Document" 
          @click="generateCommissionReport"
        >
          生成报表
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <CommissionStats :stats="stats" />

    <!-- 提成配置 -->
    <CommissionConfig
      v-model="commissionConfig"
      :all-salespersons="salespersons"
      @save="saveCommissionConfig"
      @refresh="refreshCommissionConfig"
    />

    <!-- 筛选条件 -->
    <CommissionFilter 
      v-model:query-params="queryParams"
      :salespersons="salespersons"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 提成列表 -->
    <CommissionTable
      :commission-report="commissionReport"
      :loading="loading"
      :pagination="pagination"
      :selected-items="selectedItems"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
      @sort="handleSort"
      @view-detail="viewCommissionDetail"
      @approve="approveCommission"
      @more-action="handleMoreAction"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @column-settings="showColumnSettings"
    />

    <!-- 提成详情对话框 -->
    <CommissionDetailDialog
      v-model="detailDialogVisible"
      :commission-item="detailItem"
      @close="handleDetailDialogClose"
    />

    <!-- 提成操作对话框 -->
    <CommissionOperationDialog
      v-model="operationDialogVisible"
      :commission-item="operationItem"
      @submit="handleOperationSubmit"
      @close="handleOperationDialogClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Money, Clock, Check, Download, Operation, 
  Document, Refresh, Search, SetUp, Sort, 
  Setting, Edit, Close, Wallet, ArrowDown 
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

// 导入拆分的组件
import CommissionStats from './commission/components/CommissionStats.vue'
import CommissionConfig from './commission/components/CommissionConfig.vue'
import CommissionFilter from './commission/components/CommissionFilter.vue'
import CommissionTable from './commission/components/CommissionTable.vue'
import CommissionDetailDialog from './commission/components/CommissionDetailDialog.vue'
import CommissionOperationDialog from './commission/components/CommissionOperationDialog.vue'

// 数据模型
interface Salesperson {
  id: number
  name: string
}

interface CommissionConfig {
  baseRate: number
  effectiveDate: string
  scope: string
  salespersons: number[]
  remark: string
}

interface CommissionReportItem {
  id: number
  salesperson: string
  salespersonId: number
  period: string
  orderCount: number
  totalAmount: number
  commissionRate: number
  commissionAmount: number
  status: string
  approvalDate: string
  paymentDate: string
  remark: string
}

interface CommissionStats {
  totalCommission: number
  pendingCommission: number
  paidCommission: number
  salespersonCount: number
  commissionTrend: number
  pendingCommissionTrend: number
  paidCommissionTrend: number
  salespersonTrend: number
}

interface QueryParams {
  dateRange: string[]
  salespersonId: string
  status: string
  minAmount: number | undefined
  maxAmount: number | undefined
  minCommission: number | undefined
  maxCommission: number | undefined
  page: number
  limit: number
}

// 响应式数据
const salespersons = ref<Salesperson[]>([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' }
])

const commissionConfig = ref<CommissionConfig>({
  baseRate: 10.00,
  effectiveDate: '2023-01-01',
  scope: 'all',
  salespersons: [],
  remark: '基础提成规则'
})

const commissionReport = ref<CommissionReportItem[]>([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const operationDialogVisible = ref(false)
const detailItem = ref<CommissionReportItem | null>(null)
const operationItem = ref<CommissionReportItem | null>(null)
const selectedItems = ref<CommissionReportItem[]>([])

const queryParams = reactive<QueryParams>({
  dateRange: ['', ''],
  salespersonId: '',
  status: '',
  minAmount: undefined,
  maxAmount: undefined,
  minCommission: undefined,
  maxCommission: undefined,
  page: 1,
  limit: 20
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 计算属性
const stats = computed(() => {
  return {
    totalCommission: commissionReport.value.reduce((sum, item) => sum + item.commissionAmount, 0),
    pendingCommission: commissionReport.value
      .filter(item => item.status === 'pending')
      .reduce((sum, item) => sum + item.commissionAmount, 0),
    paidCommission: commissionReport.value
      .filter(item => item.status === 'paid')
      .reduce((sum, item) => sum + item.commissionAmount, 0),
    salespersonCount: salespersons.value.length,
    commissionTrend: 0,
    pendingCommissionTrend: 0,
    paidCommissionTrend: 0,
    salespersonTrend: 0
  }
})

// 方法
const getCommissionStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'info'
    case 'approved': return 'primary'
    case 'paid': return 'success'
    case 'rejected': return 'danger'
    default: return 'info'
  }
}

const getCommissionStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待审核'
    case 'approved': return '已审核'
    case 'paid': return '已发放'
    case 'rejected': return '已拒绝'
    default: return '未知'
  }
}

const saveCommissionConfig = (config: CommissionConfig) => {
  commissionConfig.value = { ...config }
  ElMessage.success('提成规则配置保存成功')
  // 实际项目中需要调用API保存配置
}

const refreshCommissionConfig = () => {
  ElMessage.info('刷新提成配置')
  // 实际项目中需要从API获取最新配置
}

const generateCommissionReport = () => {
  loading.value = true
  try {
    // 模拟API调用
    setTimeout(() => {
      commissionReport.value = [
        {
          id: 1,
          salesperson: '张三',
          salespersonId: 1,
          period: '2023-01-01 至 2023-01-31',
          orderCount: 15,
          totalAmount: 1500000.00,
          commissionRate: 10.00,
          commissionAmount: 150000.00,
          status: 'approved',
          approvalDate: '2023-02-01',
          paymentDate: '',
          remark: '一月份提成'
        },
        {
          id: 2,
          salesperson: '李四',
          salespersonId: 2,
          period: '2023-01-01 至 2023-01-31',
          orderCount: 12,
          totalAmount: 1200000.00,
          commissionRate: 10.00,
          commissionAmount: 120000.00,
          status: 'pending',
          approvalDate: '',
          paymentDate: '',
          remark: '一月份提成'
        },
        {
          id: 3,
          salesperson: '王五',
          salespersonId: 3,
          period: '2023-01-01 至 2023-01-31',
          orderCount: 8,
          totalAmount: 800000.00,
          commissionRate: 10.00,
          commissionAmount: 80000.00,
          status: 'paid',
          approvalDate: '2023-01-15',
          paymentDate: '2023-01-20',
          remark: '一月份提成'
        }
      ]
      pagination.total = commissionReport.value.length
      loading.value = false
      ElMessage.success('提成报表生成成功')
    }, 500)
  } catch (error) {
    ElMessage.error('生成提成报表失败')
    loading.value = false
  }
}

const handleSearch = () => {
  ElMessage.info('筛选报表')
  generateCommissionReport()
}

const handleReset = () => {
  Object.assign(queryParams, {
    dateRange: ['', ''],
    salespersonId: '',
    status: '',
    minAmount: undefined,
    maxAmount: undefined,
    minCommission: undefined,
    maxCommission: undefined
  })
  generateCommissionReport()
}

const exportCommissionReport = () => {
  ElMessage.success('导出提成报表成功')
}

const showBatchOperations = () => {
  ElMessageBox.alert('批量操作功能待实现', '提示', {
    confirmButtonText: '确定'
  })
}

const handleSelectionChange = (selection: CommissionReportItem[]) => {
  selectedItems.value = selection
}

const handleRowClick = (row: CommissionReportItem) => {
  viewCommissionDetail(row)
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  ElMessage.info(`按 ${sort.prop} ${sort.order} 排序`)
}

const handleSort = (field: string) => {
  ElMessage.info(`按 ${field} 排序`)
}

const viewCommissionDetail = (item: CommissionReportItem) => {
  detailItem.value = item
  detailDialogVisible.value = true
}

const approveCommission = (item: CommissionReportItem) => {
  operationItem.value = item
  operationDialogVisible.value = true
}

const handleMoreAction = (command: { action: string, row: CommissionReportItem }) => {
  switch (command.action) {
    case 'export':
      ElMessage.info('导出明细功能待实现')
      break
    case 'adjust':
      operationItem.value = command.row
      operationDialogVisible.value = true
      break
    case 'reject':
      ElMessageBox.confirm(`确定要拒绝 ${command.row.salesperson} 的提成申请吗？`, '拒绝提成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success('提成已拒绝')
        generateCommissionReport()
      })
      break
    case 'pay':
      operationItem.value = command.row
      operationDialogVisible.value = true
      break
  }
}

const handleOperationSubmit = (formData: any) => {
  try {
    switch (formData.action) {
      case 'approve':
        ElMessage.success('提成审核通过')
        break
      case 'reject':
        ElMessage.success('提成已拒绝')
        break
      case 'adjust':
        ElMessage.success('提成金额已调整')
        break
      case 'pay':
        ElMessage.success('提成已发放')
        break
    }
    generateCommissionReport()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  generateCommissionReport()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  generateCommissionReport()
}

const showColumnSettings = () => {
  ElMessageBox.alert('列设置功能待实现', '提示', {
    confirmButtonText: '确定'
  })
}

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false
  detailItem.value = null
}

const handleOperationDialogClose = () => {
  operationDialogVisible.value = false
  operationItem.value = null
}

// 生命周期
onMounted(() => {
  generateCommissionReport()
})
</script>

<style scoped>
.commission-management {
  background-color: #ffffff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left {
  flex: 1;
}

.page-title {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
}

.status-badges {
  display: flex;
  gap: 12px;
}

.status-badges .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .commission-management {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .status-badges {
    flex-wrap: wrap;
  }
  
  .header-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>